//
//  LocationViewController.m
//  iStore
//
//  Created by MacDev on 15/4/16.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "LocationViewController.h"
#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import <BaiduMapAPI/BMKMapView.h>//只引入所需的单个头文件
#import "RequestEngine.h"
#import "CLLocation+YCLocation.h"

@interface LocationViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,
    UISearchBarDelegate>
{
    
    BMKMapView* _mapView;
    BMKLocationService* _locService;
    BMKAddressComponent * _addRess;
    BMKPoiSearch* _poisearch;
    
    
    UILabel *_lable;
}

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@end

@implementation LocationViewController
static CGFloat _locaLatitude;//纬度
static CGFloat _locaLongitude;//经度

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择店铺地址";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    _lable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_searchBar.bounds), ScreenWidth, 40)];
    _lable.backgroundColor = [UIColor colorWithWhite:0 alpha:.5];
    _lable.textColor = [UIColor whiteColor];
    [_lable setFont:[UIFont systemFontOfSize:12]];
    _lable.text = @"地址:";
    [self.view addSubview:_lable];
    
    //百度地图定位
    [self localUser];
    
    
    //定位
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];


}


#pragma mark - Local
- (void) localUser{
    
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64)];
    _mapView.mapType = BMKMapTypeStandard;
    _mapView.zoomLevel = 16;
    
    [self.view insertSubview:_mapView atIndex:0];
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
    {
        self.navigationController.navigationBar.translucent = NO;
    }

    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
 //   _mapView.showsUserLocation = YES;//显示定位图层

    
    
}
- (void) back{

    //本地化地理位置
    [[NSUserDefaults standardUserDefaults] setObject:_lable.text forKey:@"addRess"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self updateAddress:_locaLatitude withLongitude:_locaLongitude];
    [self dismissViewControllerAnimated:YES completion:nil];
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    _geocodesearch.delegate=self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _poisearch.delegate = self;
    _searchBar.delegate = self;
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _geocodesearch.delegate = nil;
    
    _poisearch.delegate = nil;
    _searchBar.delegate = nil;
}
#pragma mark --获取周围信息--
- (void)getNearBy
{
    //转坐标
//    CLLocationCoordinate2D test = CLLocationCoordinate2DMake(_locaLatitude, _locaLongitude);
//    NSDictionary* testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_COMMON);
//    
//    CLLocationCoordinate2D lo = BMKCoorDictionaryDecode(testdic);
    CLLocation *cll = [[[CLLocation alloc]initWithLatitude:_locaLatitude longitude:_locaLongitude] locationEarthFromBaidu];

    
    //请求附近WEME用户
    NSDictionary *dic =@{@"longtitude":[NSString stringWithFormat:@"%.2f",floor(cll.coordinate.longitude*100)/100],@"latitude":[NSString stringWithFormat:@"%.2f",floor(cll.coordinate.latitude*100)/100],@"appKey":@"IOS"};
    [RequestEngine RequestEngineWithDic:dic URL:@"/shop/getNearBy" completed:^(NSString *errorcode, NSDictionary *resultDict) {
        if ([errorcode isEqualToString:@"0"]) {
            NSMutableArray *coordinateArray = [[NSMutableArray alloc]init];
            for (id obj in resultDict) {
                [coordinateArray addObject:obj];
            }
 //           NSLog(@"coordinateArray.count=%lu",(unsigned long)coordinateArray.count);
            [self addPointAnnotation:coordinateArray];
 //           [_mapView showAnnotations:_mapView.annotations animated:YES];
        }
    }];

}
#pragma mark --添加标注--
- (void)addPointAnnotation:(NSMutableArray*)coordinateArray
{
    NSMutableArray *annotationArray = [[NSMutableArray alloc]init];
    int i=0;
    for (i=0; i<coordinateArray.count; i++) {
        BMKPointAnnotation* pointAnnotation = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D coor;
        coor.latitude = [[[coordinateArray objectAtIndex:i]objectForKey:@"latitude"] floatValue];
        coor.longitude = [[[coordinateArray objectAtIndex:i]objectForKey:@"longtitude"] floatValue];
        pointAnnotation.title = [[coordinateArray objectAtIndex:i]objectForKey:@"accountID"];
        pointAnnotation.subtitle = @"微密用户";
        
        //转为百度坐标
        CLLocationCoordinate2D test = CLLocationCoordinate2DMake(coor.latitude, coor.longitude);
        NSDictionary* testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_COMMON);
        
        CLLocationCoordinate2D lo = BMKCoorDictionaryDecode(testdic);
        CLLocation *cll = [[[CLLocation alloc]initWithLatitude:lo.latitude longitude:lo.longitude] locationMarsFromEarth];
        pointAnnotation.coordinate = cll.coordinate;
        [annotationArray addObject:pointAnnotation];

    }
    [_mapView addAnnotations:annotationArray];
    
}
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    NSString *AnnotationViewID = @"renameMark";
    BMKAnnotationView *newAnnotation;
    
   
    if (newAnnotation == nil) {
        newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];

        
        if ([annotation.subtitle isEqualToString:@"微密用户"]) {
            //设置样式
            newAnnotation.image = [UIImage imageNamed:@"daokeuser.png"];
            // 从天上掉下效果
            ((BMKPinAnnotationView*)newAnnotation).animatesDrop = YES;
        }
        else{
            //设置样式
            newAnnotation.image = [UIImage imageNamed:@"mark.png"];
            // 从天上掉下效果
            ((BMKPinAnnotationView*)newAnnotation).animatesDrop = NO;
        }
        
        // 设置可拖拽
        ((BMKPinAnnotationView*)newAnnotation).draggable = YES;
        
       
    }
    return newAnnotation;
}
-(UIImage *)getImageFromView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark --定位--

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"didUpdateUserLocation 纬度:lat %f,经度：long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    _locaLatitude = userLocation.location.coordinate.longitude;
    _locaLongitude = userLocation.location.coordinate.latitude;
    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    
    pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
 //       NSLog(@"反geo检索发送成功");
    }
    else
    {
 //       NSLog(@"反geo检索发送失败");
    }
    NSString *title = _lable.text;
    userLocation.subtitle = title;
    
 //   _mapView.showsUserLocation = YES;//显示定位图层
    [_mapView updateLocationData:userLocation];
    
    [_locService stopUserLocationService];
    
}
/**
 *返回反地理编码搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果
 *@param error 错误号，@see BMKSearchErrorCode
 */
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;

        _locaLatitude = result.location.latitude;
        _locaLongitude = result.location.longitude;
        /*
         
         /// 街道号码
         @property (nonatomic, strong) NSString* streetNumber;
         /// 街道名称
         @property (nonatomic, strong) NSString* streetName;
         /// 区县名称
         @property (nonatomic, strong) NSString* district;
         /// 城市名称
         @property (nonatomic, strong) NSString* city;
         /// 省份名称
         @property (nonatomic, strong) NSString* province;
         
         */
        
        if([result.addressDetail.province isEqualToString:@"北京市"] || [result.addressDetail.province isEqualToString:@"重庆市"]|| [result.addressDetail.province isEqualToString:@"天津市"] || [result.addressDetail.province isEqualToString:@"上海市"]){
        
        
            result.addressDetail.province = @"";
        }
        
        NSString *address = [NSString stringWithFormat:@"地址:%@%@%@%@%@",result.addressDetail.province,result.addressDetail.city,result.addressDetail.district,result.addressDetail.streetName,result.addressDetail.streetNumber];
        

        if(![address isEqualToString:@""]){
            

            _lable.text = address;
            _lable.textAlignment = NSTextAlignmentCenter;
            
        }
        [self getNearBy];
 //       _mapView.showsUserLocation = YES;
    }
}
/**
 *返回地址信息搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结BMKGeoCodeSearch果
 *@param error 错误号，@see BMKSearchErrorCode
 */
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        if (error == 0) {
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = result.location;
            item.title = result.address;
            [_mapView addAnnotation:item];
            _mapView.centerCoordinate = result.location;
//            NSString* titleStr;
//            NSString* showmeg;
            
//            titleStr = @"正向地理编码";
//            showmeg = [NSString stringWithFormat:@"经度:%f,纬度:%f",item.coordinate.latitude,item.coordinate.longitude];
        
        //NSLog(@"result--------- %f,%f",result.location.latitude,result.location.longitude);
        _locaLatitude = item.coordinate.latitude;
        _locaLongitude = item.coordinate.longitude;
            
            
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        
        pt = (CLLocationCoordinate2D){item.coordinate.latitude, item.coordinate.longitude};
        
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
   //         NSLog(@"反geo检索发送成功");
        }
        else
        {
   //         NSLog(@"反geo检索发送失败");
        }
        
 //       _mapView.showsUserLocation = YES;//显示定位图层
        //[_mapView updateLocationData:userLocation];
        }
    }
    else {
        alert(@"抱歉，未找到结果");
    }
}
#pragma mark - search
//点击空白处搜索
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    
    //初始化检索对象
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = coordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
 //       NSLog(@"反geo检索发送成功");
    }
    else
    {
  //      NSLog(@"反geo检索发送失败");
    }
    [_searchBar resignFirstResponder];
}
//输入框搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];

    //初始化检索对象

    BMKGeoCodeSearchOption *geoCodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    
    //    geoCodeSearchOption.city= @"北京市";
    geoCodeSearchOption.address = searchBar.text;
    BOOL flag = [_geocodesearch geoCode:geoCodeSearchOption];
    
    if(flag)
    {
  //      NSLog(@"geo检索发送成功");
    }
    else
    {
   //     NSLog(@"geo检索发送失败");
    }
    [searchBar resignFirstResponder];

    
}


#pragma mark - longitude and latitude
- (void) updateAddress:(CGFloat)latitude withLongitude:(CGFloat)longitude{

    //转坐标
//    CLLocationCoordinate2D test = CLLocationCoordinate2DMake(38.049129, 114.552582);
//    NSDictionary* testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_COMMON);
//    
//    CLLocationCoordinate2D lo = BMKCoorDictionaryDecode(testdic);
    CLLocation *cll = [[[CLLocation alloc]initWithLatitude:latitude longitude:longitude] locationEarthFromBaidu];
    
    NSString *latitudes= [NSString stringWithFormat:@"%.2f",floor(cll.coordinate.latitude*100)/100];
    NSString *longitudes = [NSString stringWithFormat:@"%.2f",floor(cll.coordinate.longitude*100)/100];
    
    
    //保存纬度
    [[NSUserDefaults standardUserDefaults] setObject:latitudes forKey:kLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //保存经度
    [[NSUserDefaults standardUserDefaults] setObject:longitudes  forKey:kLongtitude];
    [[NSUserDefaults standardUserDefaults] synchronize];


}


- (void)dealloc {
    
    if (_geocodesearch != nil) {
        _geocodesearch = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}
@end